﻿using JumpKick.HttpLib;
using Newtonsoft.Json;
using SharpEncrypt4.Lib;
using SharpEncrypt4l_Lib;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Runtime.Caching;
using System.Text;
using YiHaoHospitalPlatform.Model;

namespace YiHaoHospitalPlatform
{
    public sealed class CommitLaboratoryInstance
    {
        #region 局部变量
        /// <summary>
        /// 检验数据缓存
        /// </summary>
        private static MemoryCache LaboratoryCache = MemoryCache.Default;
        /// <summary>
        /// 要提交的检验列表
        /// </summary>
        private static List<Laboratory> laboratoryList = new List<Laboratory>();
        /// <summary>
        /// 公钥
        /// </summary>
        private static string publicKey;
        /// <summary>
        /// 平台接口地址
        /// </summary>
        private static string platformUrl;
        /// <summary>
        /// 平台分配的机构代码
        /// </summary>
        private static string orgId;
        /// <summary>
        /// 缓存时间
        /// </summary>
        private static int cacheMinutes = 600;
        /// <summary>
        /// 检索标本信息action
        /// </summary>
        private static Action QueryLaboratoryAction;
        /// <summary>
        /// 成功action
        /// </summary>
        private static Action<string> LoopCommitAction = new Action<string>(commitLaboratory);
        /// <summary>
        /// 失败action
        /// </summary>
        private static Action<WebException> FailLoopCommitAction = new Action<WebException>(RetryCommitLaboratory);
        #endregion
        #region 单利模式
        private static readonly Lazy<CommitLaboratoryInstance> instance = new Lazy<CommitLaboratoryInstance>(() =>
        {
            if (publicKey == null)
            {
                publicKey = ConfigurationManager.AppSettings["publicKey"];
            }
            if (platformUrl == null)
                platformUrl = ConfigurationManager.AppSettings["platform_url"];
            if (orgId == null)
                orgId = ConfigurationManager.AppSettings["org_id"];
            cacheMinutes = int.Parse(ConfigurationManager.AppSettings["laboratory_cache_minutes"]);
            return new CommitLaboratoryInstance();
        });
        private CommitLaboratoryInstance() { }
        public static CommitLaboratoryInstance Instance
        {
            get
            {
                return instance.Value;
            }
        }
        #endregion

        /// <summary>
        /// 设置本地检索数据的action
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public CommitLaboratoryInstance setQueryLaboratoryAction(Action action)
        {
            QueryLaboratoryAction = action;
            return Instance;
        }
        /// <summary>
        /// 向服务器提交数据，只需调用一次，内部会循环调用获取数据的方法
        /// </summary>
        /// <param name="patients">病人列表</param>
        /// <returns></returns>
        public bool StartCommitLaboratories(List<Laboratory> laboratories)
        {
            if (QueryLaboratoryAction == null)
                throw new Exception("请先设置QueryLaboratoryAction");
            if (laboratories != null)
                //组织要提交的数据
                foreach (Laboratory laboratory in laboratories)
                {
                    //判断缓存中是否有该数据
                    Laboratory cache = LaboratoryCache[laboratory.XMBZ] as Laboratory;
                    if (cache == null)
                    {
                        laboratory.isNew = true;
                        laboratoryList.Add(laboratory);
                        AddCache(laboratory);
                    }
                    else if (!cache.Equals(laboratory))
                    {
                        laboratory.isNew = false;
                        laboratoryList.Add(laboratory);
                        AddCache(laboratory);
                    }
                }
            commitLaboratory(null);
            return true;
        }

        private static void RetryCommitLaboratory(WebException ex)
        {
            commitLaboratory(null);
        }
        /// <summary>
        /// 递归调用，向服务器逐条提交数据
        /// </summary>
        private static void commitLaboratory(string commitSuccess)
        {
            if (laboratoryList.Count > 0 && commitSuccess != null)
                laboratoryList.RemoveAt(0);
            if (laboratoryList.Count > 0)
            {
                string json = JsonConvert.SerializeObject(laboratoryList[0]);
                Console.WriteLine(json);
                string encryptPatient = EncryptProvider.RSAEncrypt(RSAKeyConvert.RSAPublicKeyJava2DotNet(publicKey), json);
                Http.Post(platformUrl).Form(new { orgId = orgId, data = encryptPatient })
                    .OnSuccess(LoopCommitAction)
                    .OnFail(FailLoopCommitAction)
                    .Go();
            }
            else
            {
                QueryLaboratoryAction.BeginInvoke(null, null);
            }
        }

        /// <summary>
        /// 向缓存中添加数据
        /// </summary>
        /// <param name="department"></param>
        private void AddCache(Laboratory labpratory)
        {
            Laboratory cache = LaboratoryCache[labpratory.XMBZ] as Laboratory;
            if (cache != null)
                LaboratoryCache.Remove(labpratory.XMBZ);
            CacheItemPolicy policy = new CacheItemPolicy();
            policy.AbsoluteExpiration = DateTime.Now.AddMinutes(cacheMinutes);//取得或设定值，这个值会指定是否应该在指定期间过后清除
            LaboratoryCache.Set(labpratory.XMBZ, labpratory, policy);
        }
    }
}
